<template>
  <div
    :class="{
      active: selectWidget && selectWidget.key === element.key && isPreView,
      cursor: isPreView,
      'widget-view': isPreView,
      'drag-widget': isPreView,
      'mobile-top-label': showMobilePage && formOptions.config.labelPosition === 'top',
      'form-position-top': formOptions.config.labelPosition === 'top',
      'form-position-right': !formOptions.config.labelPosition || formOptions.config.labelPosition === 'right'
    }"
    @click="handleSelectWidget(element, $event)">
    <el-form-item
      v-if="element && element.key && !['title','titleExplain', 'subform', 'linkForm', 'associatedApproval'].includes(element.type)"
      :ref="`formItem-${element.key}`"
      :rules="(!isDetail && (element.options && element.options.required || !!(requiredKeys && requiredKeys.includes(element.key))))?[{ required: true,validator: validatorFun, trigger: 'change' }]:[]"
      :label="!element.options.isHideField ? element.name : null"
      :class="itemClass"
      prop="value"
    >
      <div
        v-if="!element.options.isHideField"
        slot="label"
        :title="element.name"
        :class="{
          'grey-label': isDetail,
          'width-require': element.options.required && !isDetail,
        }"
        class="flex-label-name">
        <span class="inner-name">{{ element.name }}</span>
        <tipIcon v-if="element.options.tip" :content="element.options.tip" :style="!showMobilePage?{marginLeft: '4px'}:{verticalAlign: 'middle'}" />
        <span v-if="isDetail">:</span>
      </div>
      <FormMakeElement
        :is-in-detail="isInDetail"
        :event-data="eventData"
        :is-detail="isDetail"
        :element="element"
        :is-middle="isMiddle"
        :is-weibo-or-weixin="isWeiboOrWeixin"
        :use-inner-upload="useInnerUpload"
        :is-pre-view="isPreView"
        :form-options="formOptions"
        style="max-width: 100%"
        @changeValueData="changeValueData"
        @clearValidate="clearValidate"
        @handleFormUserSelect="handleFormUserSelect"/>
      <div
        v-if="element.options.isRemark"
        :style="!showMobilePage?{width: (element.options.width || 240) + 'px' }:''"
        :class="{'is-detail': isDetail}"
        class="remark-input">
        <el-input
          v-if="!isDetail"
          v-model="element.options.remark"
          :maxlength="50"
          placeholder="请输入备注"
          size="small"
        />
        <ToolTip v-else-if="isDetail && element.options.remark" :content="element.options.remark" />
      </div>
    </el-form-item>
    <template v-else-if="element.type === 'subform'">
      <SubTableView v-if="isPreView" v-model="element.value" :element="element" />
      <SubTableContent
        v-else
        :is-in-detail="isInDetail"
        :is-weibo-or-weixin="isWeiboOrWeixin"
        :use-inner-upload="useInnerUpload"
        :process-status="processStatus"
        :required-keys="requiredKeys"
        :is-edit="!isDetail"
        v-model="element.value"
        :form-options="formOptions"
        :element="element"
        @selectHistory="selectHistory"
        @handleFormUserSelect="handleFormUserSelect" />
    </template>
    <template v-else-if="element.type === 'linkForm'">
      <LinkFormView v-if="isPreView" :element="element" />
      <LinkFormContent v-else :is-detail="isDetail" v-model="element.value" :element="element" :required-keys="requiredKeys" />
    </template>
    <template v-else-if="element.type === 'associatedApproval'">
      <BanAssociatedView v-if="isPreView" :element="element" />
      <BanAssociatedContent v-else :is-detail="isDetail" v-model="element.value" :element="element" :need-set-data="true" :required-keys="requiredKeys" @setListData="setListData($event, element)"/>
    </template>
    <template v-else-if="element.type === 'titleExplain'">
      <TitleExplain :style="isPreView?'padding: 0 20px;':''" :is-pre-view="isPreView" :value="element.value" />
    </template>
    <Title v-else-if="element.type === 'title'" :class="{'mb10': !isPreView}" :style="{marginLeft: isPreView?'10px':'', marginTop: getTitleTop(element.options)}" :element="element" class="title-container">
      <el-tooltip v-if="element.options && element.options.requireTitleRemark && element.options.titleRemarkWay === 0" placement="top" effect="dark">
      <div slot="content" style="max-width: 210px">{{ element.options.titleRemarkContent }}</div>
      <tipIcon is-diy style="margin-left:4px;"/>
      </el-tooltip>
      <div v-if="element.options && element.options.requireTitleRemark && element.options.titleRemarkWay === 1" class="flex-center">
      <tipIcon is-diy style="margin-left:4px;"/>
      <span class="remark">{{ element.options.titleRemarkContent }}</span>
      </div>
    </Title>
    <!-- 操作 -->
    <template v-if="isPreView">
      <div v-if="element.type !== 'subform' && element.type !== 'linkForm'" class="form-mask" />
      <div v-if="selectWidget && selectWidget.key == element.key" :class="{bottom: ['subform', 'linkForm', 'associatedApproval'].includes(element.type)}" class="widget-view-action">
        <!-- <div class="icon drag-widget"><i class="el-icon-rank font13" /></div> -->
        <img :src="copyIcon" class="icon" alt="复制" @click.stop="handleWidgetClone(element)">
        <img :src="deleteIcon" class="icon" alt="删除" @click.stop="handleWidgetDelete(element)">
      </div>
    </template>
  </div>

</template>

<script>
import { mapState } from 'vuex';
import Title from './Title';
import SubTableView from './SubTableView';
import SubTableContent from './SubTableContent';
import TitleExplain from './TitleExplain';

import LinkFormView from './linkFormView';
import LinkFormContent from './linkFormContent';
import BanAssociatedView from './BanAssociatedView';
import BanAssociatedContent from './BanAssociatedContent';
import FormMakeElement from './FormMakeElement';
import { mathFormula } from '@/utils/formMakeUtils';
import { initMathFormulaFunction } from '@/utils/formulaMath.js';

import copyIcon from '@/assets/auditProcess/copy_form.png';
import deleteIcon from '@/assets/auditProcess/delete_form.png';

export default {
  name: 'FormMakeItem',
  components: {
    Title,
    SubTableView,
    SubTableContent,
    FormMakeElement,
    LinkFormView,
    LinkFormContent,
    BanAssociatedView,
    BanAssociatedContent,
    TitleExplain
  },
  props: {
    element: {
      type: Object,
      default: null
    },
    isPreView: { // 是否配置中
      type: Boolean,
      default: false
    },
    isWeiboOrWeixin: { // 是否双微发文审核，区别是上传的接口不同
      type: Boolean,
      default: false
    },
    useInnerUpload: { // 是否使用内网上传
      type: Boolean,
      default: false
    },
    isMiddle: {
      type: Boolean,
      default: false
    },
    isDetail: { // 是否详情页展示
      type: Boolean,
      default: false
    },
    isInDetail: { // 是否详情页展示，isDetail可能因为事件而改变，导致实际在详情页而 isDetail 为false，这个属性不会改变，详情页永远为true
      type: Boolean,
      default: false
    },
    eventData: { // 事件
      type: Object,
      default: null
    },
    formOptions: {
      type: Object,
      default: () => ({})
    },
    subFormObj: {
      type: Object,
      default: () => ({})
    },
    processStatus: {// 审批详情状态
      type: Number,
      default: null
    },
    requiredKeys: {
      type: String,
      default: ''
    },
    index: {
      type: Number,
      default: null
    }
  },
  data() {
    const validatorFun = () => {
      return (rule, value, callback) => {
        if (this.isPreView) callback();

        const element = this.element;
        const isDisabled = element.options ? element.options.disabled : false;
        let data = element.value;
        const msg = `${element.name}为必填`;
        const arrVal = Array.isArray(data) && data.length === 0;
        let richeditorValidate;
        if (element.type === 'richEditor') {
          richeditorValidate = element.options.readonly ? false : data === '<p><br></p>' || data === '';
          if (data === '') {
            data = '<p><br></p>';
          }
        }
        if (!isDisabled && !data && data !== 0 || arrVal || JSON.stringify(data) === '{}' || richeditorValidate) {
          callback(new Error(msg));
        } else {
          callback();
        }
      };
    };
    return {
      validatorFun: validatorFun(),
      copyIcon, deleteIcon,
      inInit: true
    };
  },
  computed: {
    ...mapState({
      'selectWidget': state => state.formMake.selectWidget,
      'showMobilePage': state => state.app.showMobilePage
    }),
    itemClass() {
      const labelPosition = this.formOptions.config.labelPosition;
      return {
        'has-remark': !this.isDetail && this.element.options.isRemark,
        'mb0': this.isDetail && labelPosition !== 'top',
        'mb10': this.isDetail && labelPosition === 'top',
        'hide-label': this.element.options.isHideField,
        'inline-item': !this.showMobilePage,
        'mobile-item': this.showMobilePage && labelPosition !== 'top',
        'mobile-richEditor': this.element.type === 'richEditor' && this.showMobilePage && !this.isDetail
      };
    }
  },
  watch: {
    'element.value': {
      handler(data, oldData) {
        if (this.element.type === 'subform' || this.element.type === 'linkForm') {
          this.handelChangeValue();
        }
      }
    }
  },
  methods: {
    handleSelectWidget(element, e) {
      if (!this.isPreView) return;
      e.stopPropagation();
      this.$store.dispatch('setSelectWidget', element);
    },
    handleWidgetClone(element) {
      this.$emit('handleWidgetClone', element);
    },
    handleWidgetDelete(element) {
      this.$emit('handleWidgetDelete', element);
    },
    selectHistory(data) {
      this.$emit('selectHistory', data);
    },
    clearValidate(key) {
      if (this.$refs[`formItem-${key}`]) {
        this.$refs[`formItem-${key}`].clearValidate();
      }
    },
    handleFormUserSelect(data) {
      this.$emit('handleFormUserSelect', data);
    },
    // 子表单或关联表单新增或删除
    handelChangeValue() {
      const element = this.element;
      if (!this.isPreView) {
        setTimeout(() => {
          this.$nextTick(() => {
            mathFormula(this.formOptions, element);
            this.changeValueData(element);
          });
        }, 10);
      }
      setTimeout(() => {
        this.$nextTick(() => {
          initMathFormulaFunction(this.formOptions, element);
        });
      }, 10);
    },
    changeValueData(element) {
      this.$emit('changeValueData', element);
    },
    setListData(val, ele) {
      ele.realValue = val;
    },
    getTitleTop(options = {}) {
      if (options.titleLevel !== 1) return '8px';
      if (this.index === 0) return this.isInDetail ? '8px' : '0px';
      return this.isInDetail ? '23px' : '14px';
    }
  }
};
</script>
<style lang="scss" scoped>
.widget-view {
  padding: 10px 0;
  position: relative;
  // border: 1px dashed rgba(170,170,170,.7);
  background-color: #fff;
  margin: 0px;
  &:hover {
    background-color: #EFF3FB;
  }
  &.active {
    background-color: #EFF3FB;
  }
  .form-mask {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 2;
    height: 100%;
    width: 100%;
  }
  &.cursor {
    cursor: pointer;
  }
  &::v-deep {
    .el-form-item {
      margin-bottom: 0;
    }

  }
  .widget-view-action{
    position: absolute;
    right: 28px;
    top: 12px;
    height: 28px;
    line-height: 28px;
    z-index: 9;
    display: flex;
    .icon {
      margin-left: 12px;
      width: 20px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }
    &.bottom {
      bottom: 12px;
      top: auto;
    }
    .font13 { font-size: 13px; }
    .font14 { font-size: 14px !important; }
  }
  .drag-widget {
    cursor: move;
  }
}
.grey-label {
  color: #999;
}
.remark {
  color: #999;
  font-size: 12px;
  font-weight: normal;
}
.title-container {
  white-space: nowrap;
  margin-right: 20px;
}
.mb10 {
  margin-bottom: 10px;
}
.mt10 {
  margin-top: 10px;
}
.mb0 {
  margin-bottom: 0;
}
.hide-label {
  &::v-deep {
    .el-form-item__content {
      margin-left: 0 !important;
    }
  }
}
::v-deep {
  .el-form-item__content {
    color: #333 !important;
  }
}
.form-position-right {
  &::v-deep {
    .inline-item{
      .el-form-item__label {
        justify-content: flex-end;
      }
    }
  }
}

.inline-item {
  .inner-name {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .flex-label-name {
    display: flex;
    align-items: center;
    max-width: 90%;
    &.width-require {
      max-width: calc(100% - 11px);
    }
  }
  &::v-deep {
    .el-form-item__label {
      display: flex;
      align-items: center;
    }
  }
}
.mobile-item {
  display: flex;
  align-items: center;
  &::v-deep {
    .el-form-item__label {
      display: flex;
      align-items: center;
      line-height: 1 !important;
    }
    .el-form-item__content {
      flex: 1;
      margin: 0 !important;
    }
  }
}
.form-position-top {
  &::v-deep {
    .el-form-item__label {
      padding-bottom: 0;
      line-height: 1.5 !important;
    }
    .widget-view {
      padding: 5px 0;
    }
  }
}
.mobile-top-label {
  ::v-deep {
    .el-form-item__label {
      display: flex !important;
    }
  }
}
.mobile-richEditor {
  flex-wrap: wrap;
    &::v-deep {
    .el-form-item__label {
      width: 100% !important;
      margin: 12px 0;
    }
    .el-form-item__content {
      width: 100%;
      flex: none;
    }
    .textbus-container {
      height: auto !important;
    }
    .textbus-ui-workbench {
      min-height: 200px !important;
    }
  }
}
.form-item-label-name {
  display: flex;
  align-items: center;
}
.has-remark {
  &::v-deep {
    .el-form-item__error {
      top: calc(100% - 50px)
    }
  }
}
.remark-input {
  margin-top: 18px;
  &::v-deep {
    .el-input__inner {
      border-color: #DCDFE6 !important;
    }
  }
  &.is-detail {
    margin-top: 0;
  }
}
</style>
